package com.ruoyi.campus.controller;

import com.ruoyi.campus.domain.AlarmRecord;
import com.ruoyi.campus.service.IAlarmRecordService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 报警记录Controller
 * 
 * @author campus-alarm
 * @date 2024-01-01
 */
@RestController
@RequestMapping("/campus/alarm")
public class AlarmRecordController extends BaseController
{
    @Autowired
    private IAlarmRecordService alarmRecordService;

    /**
     * 查询报警记录列表
     */
    @PreAuthorize("@ss.hasPermi('campus:alarm:list')")
    @GetMapping("/list")
    public TableDataInfo list(AlarmRecord alarmRecord)
    {
        startPage();
        List<AlarmRecord> list = alarmRecordService.selectAlarmRecordList(alarmRecord);
        return getDataTable(list);
    }

    /**
     * 查询待处理的报警记录
     */
    @PreAuthorize("@ss.hasPermi('campus:alarm:list')")
    @GetMapping("/pending")
    public AjaxResult pendingAlarms(@RequestParam(required = false) Long schoolId)
    {
        List<AlarmRecord> list = alarmRecordService.selectPendingAlarmRecords(schoolId);
        return AjaxResult.success(list);
    }

    /**
     * 查询紧急报警记录
     */
    @PreAuthorize("@ss.hasPermi('campus:alarm:list')")
    @GetMapping("/emergency")
    public AjaxResult emergencyAlarms(@RequestParam(required = false) Long schoolId)
    {
        List<AlarmRecord> list = alarmRecordService.selectEmergencyAlarmRecords(schoolId);
        return AjaxResult.success(list);
    }

    /**
     * 查询实时报警数据（最近24小时）
     */
    @PreAuthorize("@ss.hasPermi('campus:alarm:list')")
    @GetMapping("/realtime")
    public AjaxResult realtimeAlarms(@RequestParam(required = false) Long schoolId)
    {
        List<AlarmRecord> list = alarmRecordService.selectRealtimeAlarmData(schoolId);
        return AjaxResult.success(list);
    }

    /**
     * 查询超时未处理的报警记录
     */
    @PreAuthorize("@ss.hasPermi('campus:alarm:list')")
    @GetMapping("/timeout")
    public AjaxResult timeoutAlarms(@RequestParam(defaultValue = "60") Integer timeoutMinutes)
    {
        List<AlarmRecord> list = alarmRecordService.selectTimeoutAlarmRecords(timeoutMinutes);
        return AjaxResult.success(list);
    }

    /**
     * 统计报警数据
     */
    @PreAuthorize("@ss.hasPermi('campus:alarm:statistics')")
    @GetMapping("/statistics")
    public AjaxResult getStatistics(@RequestParam(required = false) Long schoolId,
                                  @RequestParam(required = false) String startTime,
                                  @RequestParam(required = false) String endTime)
    {
        Date start = DateUtils.parseDate(startTime);
        Date end = DateUtils.parseDate(endTime);
        Map<String, Object> statistics = alarmRecordService.selectAlarmStatistics(schoolId, start, end);
        return AjaxResult.success(statistics);
    }

    /**
     * 按时间段统计报警数量
     */
    @PreAuthorize("@ss.hasPermi('campus:alarm:statistics')")
    @GetMapping("/statistics/time")
    public AjaxResult getTimeStatistics(@RequestParam(required = false) Long schoolId,
                                      @RequestParam(required = false) String startTime,
                                      @RequestParam(required = false) String endTime,
                                      @RequestParam(defaultValue = "day") String groupBy)
    {
        Date start = DateUtils.parseDate(startTime);
        Date end = DateUtils.parseDate(endTime);
        List<Map<String, Object>> statistics = alarmRecordService.selectAlarmCountByTime(schoolId, start, end, groupBy);
        return AjaxResult.success(statistics);
    }

    /**
     * 按报警类型统计
     */
    @PreAuthorize("@ss.hasPermi('campus:alarm:statistics')")
    @GetMapping("/statistics/type")
    public AjaxResult getTypeStatistics(@RequestParam(required = false) Long schoolId,
                                      @RequestParam(required = false) String startTime,
                                      @RequestParam(required = false) String endTime)
    {
        Date start = DateUtils.parseDate(startTime);
        Date end = DateUtils.parseDate(endTime);
        List<Map<String, Object>> statistics = alarmRecordService.selectAlarmCountByType(schoolId, start, end);
        return AjaxResult.success(statistics);
    }

    /**
     * 按地理位置统计报警热点
     */
    @PreAuthorize("@ss.hasPermi('campus:alarm:statistics')")
    @GetMapping("/statistics/hotspots")
    public AjaxResult getHotspots(@RequestParam(required = false) Long schoolId,
                                @RequestParam(required = false) String startTime,
                                @RequestParam(required = false) String endTime)
    {
        Date start = DateUtils.parseDate(startTime);
        Date end = DateUtils.parseDate(endTime);
        List<Map<String, Object>> hotspots = alarmRecordService.selectAlarmHotspots(schoolId, start, end);
        return AjaxResult.success(hotspots);
    }

    /**
     * 导出报警记录列表
     */
    @PreAuthorize("@ss.hasPermi('campus:alarm:export')")
    @Log(title = "报警记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AlarmRecord alarmRecord)
    {
        List<AlarmRecord> list = alarmRecordService.selectAlarmRecordList(alarmRecord);
        ExcelUtil<AlarmRecord> util = new ExcelUtil<AlarmRecord>(AlarmRecord.class);
        util.exportExcel(response, list, "报警记录数据");
    }

    /**
     * 获取报警记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('campus:alarm:query')")
    @GetMapping(value = "/{alarmId}")
    public AjaxResult getInfo(@PathVariable("alarmId") Long alarmId)
    {
        return AjaxResult.success(alarmRecordService.selectAlarmRecordByAlarmId(alarmId));
    }

    /**
     * 获取报警记录详细信息（包含关联信息）
     */
    @PreAuthorize("@ss.hasPermi('campus:alarm:query')")
    @GetMapping(value = "/detail/{alarmId}")
    public AjaxResult getDetailInfo(@PathVariable("alarmId") Long alarmId)
    {
        return AjaxResult.success(alarmRecordService.selectAlarmRecordDetail(alarmId));
    }

    /**
     * 新增报警记录
     */
    @PreAuthorize("@ss.hasPermi('campus:alarm:add')")
    @Log(title = "报警记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody AlarmRecord alarmRecord)
    {
        alarmRecord.setCreateBy(getUsername());
        return toAjax(alarmRecordService.insertAlarmRecord(alarmRecord));
    }

    /**
     * 修改报警记录
     */
    @PreAuthorize("@ss.hasPermi('campus:alarm:edit')")
    @Log(title = "报警记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody AlarmRecord alarmRecord)
    {
        alarmRecord.setUpdateBy(getUsername());
        return toAjax(alarmRecordService.updateAlarmRecord(alarmRecord));
    }

    /**
     * 删除报警记录
     */
    @PreAuthorize("@ss.hasPermi('campus:alarm:remove')")
    @Log(title = "报警记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{alarmIds}")
    public AjaxResult remove(@PathVariable Long[] alarmIds)
    {
        return toAjax(alarmRecordService.deleteAlarmRecordByAlarmIds(alarmIds));
    }

    /**
     * 分配报警处理人
     */
    @PreAuthorize("@ss.hasPermi('campus:alarm:assign')")
    @Log(title = "报警记录", businessType = BusinessType.UPDATE)
    @PutMapping("/assign")
    public AjaxResult assignHandler(@RequestParam Long alarmId, @RequestParam Long handlerUserId)
    {
        return toAjax(alarmRecordService.assignAlarmHandler(alarmId, handlerUserId));
    }

    /**
     * 开始处理报警
     */
    @PreAuthorize("@ss.hasPermi('campus:alarm:handle')")
    @Log(title = "报警记录", businessType = BusinessType.UPDATE)
    @PutMapping("/startHandle")
    public AjaxResult startHandle(@RequestParam Long alarmId)
    {
        Long handlerUserId = getUserId();
        return toAjax(alarmRecordService.startHandleAlarm(alarmId, handlerUserId));
    }

    /**
     * 完成报警处理
     */
    @PreAuthorize("@ss.hasPermi('campus:alarm:handle')")
    @Log(title = "报警记录", businessType = BusinessType.UPDATE)
    @PutMapping("/completeHandle")
    public AjaxResult completeHandle(@RequestParam Long alarmId, @RequestParam String handleResult)
    {
        return toAjax(alarmRecordService.completeAlarmHandle(alarmId, handleResult));
    }

    /**
     * 关闭报警
     */
    @PreAuthorize("@ss.hasPermi('campus:alarm:close')")
    @Log(title = "报警记录", businessType = BusinessType.UPDATE)
    @PutMapping("/close")
    public AjaxResult closeAlarm(@RequestParam Long alarmId, @RequestParam String closeReason)
    {
        return toAjax(alarmRecordService.closeAlarm(alarmId, closeReason));
    }

    /**
     * 批量更新报警状态
     */
    @PreAuthorize("@ss.hasPermi('campus:alarm:edit')")
    @Log(title = "报警记录", businessType = BusinessType.UPDATE)
    @PutMapping("/updateStatusBatch")
    public AjaxResult updateStatusBatch(@RequestParam Long[] alarmIds, 
                                      @RequestParam Integer handleStatus, 
                                      @RequestParam(required = false) Long handlerUserId)
    {
        return toAjax(alarmRecordService.updateAlarmStatusBatch(alarmIds, handleStatus, handlerUserId));
    }

    /**
     * 转接报警
     */
    @PreAuthorize("@ss.hasPermi('campus:alarm:transfer')")
    @Log(title = "报警记录", businessType = BusinessType.UPDATE)
    @PutMapping("/transfer")
    public AjaxResult transferAlarm(@RequestParam Long alarmId, 
                                  @RequestParam Long newHandlerUserId, 
                                  @RequestParam String transferReason)
    {
        return toAjax(alarmRecordService.transferAlarm(alarmId, newHandlerUserId, transferReason));
    }

    /**
     * 升级报警等级
     */
    @PreAuthorize("@ss.hasPermi('campus:alarm:upgrade')")
    @Log(title = "报警记录", businessType = BusinessType.UPDATE)
    @PutMapping("/upgrade")
    public AjaxResult upgradeAlarmLevel(@RequestParam Long alarmId, 
                                      @RequestParam Integer newLevel, 
                                      @RequestParam String upgradeReason)
    {
        return toAjax(alarmRecordService.upgradeAlarmLevel(alarmId, newLevel, upgradeReason));
    }
} 